package com.spring.security.study.security_test.config;

import com.spring.security.study.security_test.api.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import cn.hutool.core.util.StrUtil;

/**
 * @ClassName : SysUserPermission
 * @Author : lby
 * @Date: 2021/1/25 15:39
 * @Description : 自定义权限注解
 */
@Slf4j
@Component("pms")
public class SysUserPermission implements PermissionEvaluator {
    /**
     *
     * @param authentication
     * @param o
     * @param o1
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        // 获取用户信息
        SysUserDetails userDetails=(SysUserDetails) authentication.getPrincipal();
        // 校验权限
        Set<String> permissions = new HashSet<String>();
        permissions.add("sys_user_view");
        if (permissions.contains(o1)){
            return true;
        }
        log.error("用户无此权限");
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }

    /**
     * 自定义权限校验
     */
    public boolean hasPermission(String permission) {
        if (StrUtil.isBlank(permission)) {
            return false;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
    }
}
